<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Repositories\User\UserRepository;
use App\Http\Requests\CreateUser;
use App\Repositories\Role\RoleRepository;

class UserController extends Controller {

	private $user;
	private $roles;


	public function __construct(UserRepository $user, RoleRepository $roles) {
		$this->user  = $user;
		$this->roles = $roles;
	}

	/**
	 * @param Request $request
	 * @return \Illuminate\View\View
	 */
	public function index(Request $request) {
		$list = $this->user->condition($request->input('search'))->paginate();
		return view('admin.user.index', compact('list'));
	}

	/**
	 * Show the form for creating a new resource.
	 * @return Response
	 */
	public function create() {
		return view('admin.user.create');
	}

	/**
	 * Store a newly created resource in storage.
	 * @param $request
	 * @return Response
	 */
	public function store(CreateUser $request) {

		$user = $this->user->create($request->all());

		if ($user) {
			success('添加成功');
		} else {
			error('添加失败');
		}
	}

	/**
	 * Display the specified resource.
	 * @param  int $id
	 * @return Response
	 */
	public function show($id) {
		$user = $this->user->find($id);
		return view('admin.user.show', compact('user'));
	}

	/**
	 * Show the form for editing the specified resource.
	 * @param  int $id
	 * @return Response
	 */
	public function edit($id) {
		//
	}

	/**
	 * Update the specified resource in storage.
	 * @param  int $id
	 * @return Response
	 */
	public function update($id) {
		//
	}

	/**
	 * Remove the specified resource from storage.
	 * @param  int $id
	 * @return Response
	 */
	public function destroy($id) {
		//
	}

	/**
	 * 分配角色
	 * @param $request
	 * @param $id
	 * @return \Illuminate\View\View
	 */
	public function AssignRole(Request $request,$id) {

		$roles = $this->roles->all(['id', 'display_name']);

		$user = $this->user->find($id);

		if ($request->isMethod('post')) {

			$roleIds = $request->input('roleIds',array());

			if ($this->user->assignRole($id,$roleIds)) {
				success('角色设置成功');
			} else {
				error('角色设置失败');
			};

		};

		return view('admin.user.assign_role', compact('id','roles','user'));
	}

	/**
	 * 封禁用户
	 * @param     $id
	 * @param int $lock
	 */
	public function lock($id,$lock = 1){
		$this->user->update(['locked'=>$lock],$id);
		success('操作成功');
	}
}
